from urllib import request, parse, error
import json

def get(url, param):
  q = parse.urlencode(param)
  req = request.Request(url + '?' + q)
  try:
    rsp = request.urlopen(req)
    str_rsp = rsp.read()
    try:
      dict_rsp = json.loads(str_rsp.decode('utf8'))
      return dict_rsp
    except json.JSONDecodeError:
      return str_rsp.decode('utf8')
  except error.HTTPError as e:
    dict_error = {}
    if hasattr(e, "code"):
      dict_error = {}
      dict_error['ret'] = -1
      dict_error['httpcode'] = e.code
      dict_error['msg'] = "sdk http get err"
      return dict_error
    if hasattr(e, "reason"):
      dict_error['msg'] = 'sdk http get err'
      dict_error['httpcode'] = -1
      dict_error['ret'] = -1
      return dict_error
  except Exception as e:
    dict_error = {}
    dict_error['ret'] = -1
    dict_error['httpcode'] = -1
    dict_error['msg'] = str(e)
    return dict_error
  else:
    dict_error = {}
    dict_error['ret'] = -1
    dict_error['httpcode'] = -1
    dict_error['msg'] = "system error"
    return dict_error

def post(url, param):
  req = request.Request(url, parse.urlencode(param).encode())
  try:
    rsp = request.urlopen(req)
    str_rsp = rsp.read()
    try:
      dict_rsp = json.loads(str_rsp.decode('utf8'))
      return dict_rsp
    except json.JSONDecodeError:
      return str_rsp.decode('utf8')
  except error.HTTPError as e:
    dict_error = {}
    if hasattr(e, "code"):
      dict_error = {}
      dict_error['ret'] = -1
      dict_error['httpcode'] = e.code
      dict_error['msg'] = "sdk http post err"
      return dict_error
    if hasattr(e, "reason"):
      dict_error['msg'] = 'sdk http post err'
      dict_error['httpcode'] = -1
      dict_error['ret'] = -1
      return dict_error
  except Exception as e:
    dict_error = {}
    dict_error['ret'] = -1
    dict_error['httpcode'] = -1
    dict_error['msg'] = str(e)
    return dict_error
  else:
    dict_error = {}
    dict_error['ret'] = -1
    dict_error['httpcode'] = -1
    dict_error['msg'] = "system error"
    return dict_error

def main():
  # url = 'http://172.17.2.25:8080/vote-record/8RJUddfrhXLLoveqk9ED'
  url = 'http://172.17.2.25:8080/query'
  q = {}
  q['q'] = 'baidu'
  ret = get(url, q)
  if 'ret' in ret and ret['ret'] < 0:
    print('error: {}'.format(str(ret)))
  else:
    print('ok: {}'.format(ret))

if __name__ == '__main__':
  main()